package mfuny.ggongal.admin.ask;

import java.util.HashMap;
import java.util.List;

import mfuny.ggongal.admin.Server;
import mfuny.ggongal.admin.debug.Debug;
import mfuny.ggongal.admin.etc.EmailSender;
import mfuny.ggongal.admin.http.HttpUser;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.springframework.web.servlet.ModelAndView;

import com.ibatis.sqlmap.client.SqlMapClient;

public class AskService {
	SqlMapClient sqlMapper;
	ModelAndView mav;
	
	public AskService() throws Exception {
		sqlMapper = Server.getSqlMapper();
		mav = new ModelAndView();
	}
	
	//문의 게시판.
	public ModelAndView askList() throws Exception {
		mav.clear();
		mav.setViewName("/ask/askList.ga");
		return mav;
	}
	
	//문의 게시판 상세 리스트.
	@SuppressWarnings("unchecked")
	public ModelAndView getAskList(String param) throws Exception {
		JSONObject jsonParam = (JSONObject) JSONValue.parse(param);
		int pageNum = jsonParam.get("num") instanceof Integer ? (Integer)jsonParam.get("num") : (int)(long)(Long)jsonParam.get("num");
		int pageSize = jsonParam.get("pageSize") instanceof Integer ? (Integer)jsonParam.get("pageSize") : 
					(int)(long)(Long)jsonParam.get("pageSize");
				
		int num = pageNum == 0 ? 1 : pageNum * pageSize - pageSize;
		jsonParam.put("num", num);
		
		List<HashMap<String, Object>> resultList = sqlMapper.queryForList("ask_selectList", jsonParam);
		int totalCount = (Integer)sqlMapper.queryForObject("ask_totalCount", jsonParam);
		
		mav.clear();
		mav.setViewName("/ask/getAskList");
		mav.addObject("resultList", resultList);
		mav.addObject("totalCount", totalCount);
		mav.addObject("pageNum", pageNum);
		return mav;
	}
	
	//특정 글 문의 내용 상세 팝업.
	@SuppressWarnings("unchecked")
	public ModelAndView ask_detailContents(int ask_no) throws Exception {
		HashMap<String, Object> resultClass = (HashMap<String, Object>) sqlMapper.queryForObject("ask_selectContents", ask_no);
		if(resultClass != null && resultClass.get("reply") != null) {
			resultClass.put("reply", ((String)resultClass.get("reply")).replaceAll("<br/>", "\n") );
		}
		mav.clear();
		mav.setViewName("/ask/ask_detailContents");
		mav.addObject("resultClass", resultClass);
		return mav;
	}
	
	//특정 글 문의 답변 보내기 폼.
	@SuppressWarnings("unchecked")
	public ModelAndView ask_replyForm(int ask_no) throws Exception {
		HashMap<String, Object> resultClass = (HashMap<String, Object>) sqlMapper.queryForObject("ask_selectContents", ask_no);
		mav.clear();
		mav.setViewName("/ask/ask_replyForm");
		mav.addObject("resultClass", resultClass);
		return mav;
	}
	
	//답변 보내기 처리.
	@SuppressWarnings({ "unchecked", "finally" })
	public ModelAndView ask_reply(String jsonParam) throws Exception {
		int result = 0;
		JSONObject json = (JSONObject) JSONValue.parse(jsonParam);
		json.put("reply", ((String)json.get("reply")).replaceAll("\n", "<br/>"));
		HashMap<String, Object> resultClass = (HashMap<String, Object>) sqlMapper.queryForObject("ask_selectContents", Integer.parseInt((String)json.get("ask_no")));
		
		StringBuffer sendStr = new StringBuffer();
		sendStr.append((String)json.get("reply"));
		sendStr.append("<br/><br/><br/><br/>--------------------- 문의하신 내용 ---------------------<br/><br/>");
		sendStr.append(((String)resultClass.get("contents")).replaceAll("\n", "<br/>"));
		
		try{
			sqlMapper.startTransaction();
			new EmailSender().sendMail(
					"admin@ggongal.com", 
					(String)resultClass.get("email"), 
					"꽁알 - 문의하신 내용 답변드립니다.", 
					sendStr.toString()
					);
			
			result = sqlMapper.update("ask_updateReply", json);
			if( result > 0 && (Boolean)json.get("giveGgong")) {
				HashMap<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("id", resultClass.get("user_id"));
				paramMap.put("ggong", 1000);
				paramMap.put("reason", "버그 신고");
				new HttpUser().user_addGgongNoTrans(paramMap);
			}
			
			sqlMapper.commitTransaction();
		}catch(Exception e){
			Debug.toDebugFile(e, "ask_reply");
			result = -1;
			
		}finally{
			sqlMapper.endTransaction();
			
			mav.clear();
			mav.setViewName("/blank");
			mav.addObject("value", result);
			return mav;
		}
	}
}
